/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package AudioAnalyzer;

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.sensor.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
import javax.microedition.media.protocol.SourceStream;
import java.io.*;
import javax.microedition.io.file.*;
import javax.microedition.io.*;
import javax.microedition.amms.control.camera.*;
import javax.microedition.amms.control.*;
import javax.microedition.amms.control.tuner.*;
import javax.microedition.amms.GlobalManager;
import javax.microedition.amms.MediaProcessor;
import javax.microedition.amms.control.imageeffect.ImageTransformControl;


/**
 *
 * @author thomas.s
 */
public class AudioAnalyzer extends MIDlet implements CommandListener {
    AudioCanvas canvas;

    public AudioAnalyzer() {
        canvas = new AudioCanvas();
    }

    public void startApp() {
        Display.getDisplay(this).setCurrent( canvas );
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void close()
    {
        Display.getDisplay(this).setCurrent(null);
        canvas = null;
        destroyApp(true);
        notifyDestroyed();
    }
    public void commandAction(Command c, Displayable s) {
    }

   class AudioCanvas extends Canvas {
       AudioAnalyzer parent;
       Player player;
       RecordControl rc;
       ByteArrayOutputStream output, raw;
       Timer timer;
       int min, max;
       byte b[];
       String type;
       int index;
       ByteArrayOutputStream jpg;
       Image bg;

       String debug[];
       boolean capturing;
       
       public AudioCanvas()
       {
           capturing=true;
           bg = null;
           debug = new String[10];
           for (int i=0; i<10; i++) debug[i]=".";
           //testRadio();
            index=0;
            repaint();
            timer = new Timer();
            timer.schedule(new updateTask(this), 0, 10000);
       }
/*
       public void testRadio()
       {
           try {
            player = Manager.createPlayer("http://ntv.ivwbox.de/cgi-bin/ivw/CP/vid_live;media/Mediathek/Livestream");
            debug[0] = player!=null ?"radio" :"no radio";
            player.start();
            
            TunerControl tuner = (TunerControl) player.getControl("TunerControl");
            debug[1] = tuner==null ? "tuner" : "no tuner";
             player.realize();

            int frequencyFound = tuner.seek(970000, TunerControl.MODULATION_FM, true);
            tuner.setStereoMode(TunerControl.STEREO);
            tuner.setPreset(1);
            tuner.setPresetName(1, "Radio 1");
            player.prefetch();
            player.start();
           } catch( Exception e ){ debug[9]="ex";}

       }

       public void testImage()
       {
           try{
               MediaProcessor mp = GlobalManager.createMediaProcessor("image/raw");
               ImageTransformControl imageEffect =
                  (ImageTransformControl)mp.getControl("javax.microedition.amms.control.imageeffect.ImageTransformControl");
              debug[3] = "control" + imageEffect==null?"failed":"ok";
             ImageFormatControl fc = (ImageFormatControl)mp.getControl("javax.microedition.amms.control.ImageFormatControl");
              debug[5] = fc==null?"failed":"ok";

             FileConnection f = (FileConnection) Connector.open("file:///mmc/Images/stonebg2.jpg");
             debug[0] = f!=null ? "f ok":"f failed";

             InputStream s = f.openInputStream();

             debug[1] = s!=null ? "stream ok" : "Stream null";
             mp.setOutput(jpg = new ByteArrayOutputStream());
             debug[2] = "setoutput ok";

             mp.setInput(s);
             debug[1] = "setinput ok";

             // Define effects to be applied during processing
             imageEffect.setTargetSize(800,480,0);
                debug[4] = "target size";

             // Set output format
             fc.setFormat("image/jpeg");
             fc.setParameter("quality", 80);

             // Do the actual processing. If you do not want to use a blocking call,
             // use start() and MediaProcessorListener.
             mp.complete();
             debug[6] = "complete";
             byte jpgb[] = jpg.toByteArray();
             debug[7]= " " + jpgb.length;
             bg = Image.createImage(jpgb,0,jpgb.length);
           } catch( Exception e  )  { bg=null; debug[9] ="ex"; }

       }
*/

       class updateTask extends TimerTask {
            private AudioCanvas canvas;
            updateTask( AudioCanvas c ){  canvas = c;  }
            public void run()
            {
                if(capturing) canvas.capture();
                canvas.repaint();
            }

       }

       public void capture()
       {

           try {
            player = Manager.createPlayer("capture://audio?encoding=audio/mpeg");
            player.realize();
            rc = (RecordControl)player.getControl("RecordControl");
            output = new ByteArrayOutputStream();
            rc.setRecordStream(output);
            player.prefetch();
            player.start();
             } catch(Exception e) {}
            rc.startRecord();
            try { Thread.currentThread().sleep(100); } catch( Exception e ){}
            try {
                player.stop();

                rc.stopRecord();
                type = rc.getContentType();
                rc.commit();
                b = output.toByteArray();
/*
                FileConnection f = (FileConnection) Connector.open("file:///mmc/amr"+index++);
                if (f.exists()) f.delete();
                f.create();
                f.openDataOutputStream().write(b,0,b.length);
*/
            } catch( Exception e ) {}
/*
          try {
            raw = new ByteArrayOutputStream();

            //Create MediaProcessor for raw Image
            MediaProcessor mediaProc = GlobalManager.createMediaProcessor(type);
            AudioFormatControl format = (AudioFormatControl)mediaProc.getControl("AudioFormatControl");
            format.setFormat("audio/pcm");
            mediaProc.setInput(output);
            mediaProc.setOutput(raw);
           // mediaProc.start();
            mediaProc.complete();
            b = raw.toByteArray();


          } catch(Exception e) {}
          */


       }
       
       public void paint(Graphics g) {
            int w = getWidth();
            int h = getHeight();
            g.setColor(0x2000);
            if (bg!=null) g.drawImage(bg,0,0,0);
            g.fillRect(0,0,w,h);
            g.setColor(0xffffff);
            for ( int i=0; i<10; i++ ) g.drawString(debug[i],0,i*30+50,0);
            if (b!=null)
            {
                g.drawString(type + ":" +b.length,0,0,0);
                for ( int i=0; i<b.length && i<h; i++ )
                    g.fillRect(200,i,b[i],1);
            }
        }
   }

}
